package us.norepeter.processing.textmatcher;

import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.PriorityQueue;
import java.util.Queue;

/**
 * Encapsulates a series of steps in which Comparisons are pruned and assigned
 * scores.
 * 
 * @author ##author##
 */
public class TextProcessingChain {

	Queue<TextProcessingChainLink> steps;
	String name;

	public TextProcessingChain(String name) {
		this(name, new LinkedList<TextProcessingChainLink>());
	}


	public TextProcessingChain(String name, Queue<TextProcessingChainLink> steps) {
		this.steps = steps;
		this.name = name;
	}

	PriorityQueue<Comparison> process(Collection<Comparison> comparisons) {
		PriorityQueue<Comparison> queue = new PriorityQueue<Comparison>();
		for (Comparison c : comparisons) {
			for (TextProcessingChainLink step : steps) {
				boolean shouldRemove = step.process(c);
				if( shouldRemove ) {
					comparisons.remove(c);
				} else {
					queue.add(c);
				}
			}
		}
		return queue;
	}
	
	Comparison[] process(Comparison[] comparisons ) {
		List<Comparison> list = Arrays.asList(comparisons);
		PriorityQueue<Comparison> queue = process( list );
	    comparisons = new Comparison[list.size()];
		int index = 0;
		for( Comparison c : list ) {
			comparisons[index++] = queue.poll();
		}
		return comparisons;
	}


	/**
	 * @param e
	 * @return
	 * @see java.util.Queue#add(java.lang.Object)
	 */
	public boolean add(TextProcessingChainLink e) {
		return steps.add(e);
	}


	/**
	 * @return
	 * @see java.util.Collection#size()
	 */
	public int size() {
		return steps.size();
	}


	/**
	 * @return
	 * @see java.util.Collection#iterator()
	 */
	public Iterator<TextProcessingChainLink> iterator() {
		return steps.iterator();
	}


	/**
	 * @param o
	 * @return
	 * @see java.util.Collection#remove(java.lang.Object)
	 */
	public boolean remove(Object o) {
		return steps.remove(o);
	}


	/**
	 * @param c
	 * @return
	 * @see java.util.Collection#addAll(java.util.Collection)
	 */
	public boolean addAll(Collection<? extends TextProcessingChainLink> c) {
		return steps.addAll(c);
	}
}
